package com.hfzy.ihk.web.linkcall.controller.setting.knowledgeBase.type;

import com.hfzy.ihk.common.util.Utils;
import com.hfzy.ihk.common.web.WebResult;
import com.hfzy.ihk.facade.linkcall.entity.BusinessTypeBase;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingPackage;
import com.hfzy.ihk.facade.linkcall.entity.knowledge.type.IndustryType;
import com.hfzy.ihk.facade.linkcall.vo.knowledgeBase.DTreeNodeVo;
import com.hfzy.ihk.facade.linkcall.vo.knowledgeBase.TreeNodeVo;
import com.hfzy.ihk.web.linkcall.biz.BusinessTypeBaseBiz;
import com.hfzy.ihk.web.linkcall.biz.KnowledgeBase.type.IndustryTypeBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingPackageBiz;
import com.hfzy.ihk.web.linkcall.utils.UserUtils;
import com.hfzy.ihk.web.linkcall.utils.WebResultUtils;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/industryType")
public class IndustryTypeController {

    @Autowired
    private IndustryTypeBiz industryTypeBiz;

    @Autowired
    private BusinessTypeBaseBiz businessTypeBaseBiz;

    @Autowired
    private SpeakingPackageBiz speakingPackageBiz;

    /**
     * 页面
     * */
    @RequestMapping("/saveOrUpdateIndustryType")
    public String saveOrUpdateIndustryType(String id,Model model){
        List<IndustryType> industryTypeList = industryTypeBiz.getAll();
        if(!Utils.isNullString(id)){
            IndustryType industryType = industryTypeBiz.selectById(id);
            if(industryType!=null){
                industryTypeList.remove(industryType);
                model.addAttribute("industryType",industryType);
            }
        }
        List<BusinessTypeBase> businessTypeBases = businessTypeBaseBiz.getAll();
        model.addAttribute("businessTypeBases",businessTypeBases);
        model.addAttribute("parentIndustryTypes",industryTypeList);
        return "page/knowledgeBase/type/saveOrUpdateIndustryType";
    }

    /**
     * 类型页面
     * */
    @RequestMapping("/queryIndustryTypes")
    public String queryIndustryType(@RequestParam Map<String, String> params){
        return "page/knowledgeBase/type/queryIndustryTypes";
    }


    /**
     * ======================================业务操作==============================================
     * */
    @ResponseBody
    @RequestMapping("/queryByPage")
    public WebResult queryByPage(@RequestParam Map<String,String> params){
        WebResult webResult = null;
        try {
            Page<IndustryType>  page = industryTypeBiz.getByPage(params);
            List<Map> list = new ArrayList<Map>();

            if(page.getContent()!=null && !page.getContent().isEmpty()){
                List<String> uids = page.getContent().stream().map(it->it.getCreateUserId()+"").collect(Collectors.toList());
                Map<Integer,String> userMap = UserUtils.getUserNameMap(uids);
                for(IndustryType industryType:page.getContent()){
                    Map<String,Object> map = new HashMap<>();
                    map.put("name",industryType.getName());
                    map.put("parentName",industryType.getParentId()!=null&&!Utils.isNullString(industryType.getParentId())&&!"0".equals(industryType.getParentId())?
                            industryTypeBiz.selectById(industryType.getParentId()).getName():"");
                    map.put("id",industryType.getId());
                    map.put("createUserName",userMap.get(industryType.getCreateUserId())!=null?userMap.get(industryType.getCreateUserId()):"系统管理员");
                    map.put("modTime",Utils.date2DateTimeString(industryType.getModTime()));
                    list.add(map);
                }
            }
            webResult = WebResultUtils.getSuccessCharWebResult("",page.getTotalElements(),list);
        }catch (Exception e){
            e.printStackTrace();
            webResult = WebResultUtils.getExceptionCharWebResult("");
        }finally {
            if(webResult==null)
                webResult = WebResultUtils.getFailCharWebResult("");
        }
        return webResult;
    }


    @ResponseBody
    @RequestMapping("/save")
    public WebResult save(@RequestParam Map<String, String> params){
        WebResult webResult= null;
        try{
            if(params!=null && !params.isEmpty()){
                IndustryType industryType = new IndustryType();
                Iterator<Map.Entry<String,String>> it = params.entrySet().iterator();
                industryType.setName(params.get("name"));
                industryType.setParentId(params.get("parentId"));
                industryType.setBusinessTypeBaseId(params.get("businessTypeBaseId"));
                if(params.containsKey("id") && !Utils.isNullString(params.get("id"))){
                    industryType.setId(params.get("id"));
                }
                webResult = industryTypeBiz.save(industryType);
                /*List<String> fNames = Arrays.stream(industryType.getClass().getFields()).map(f->f.getName()).collect(Collectors.toList());
                while (it.hasNext()){
                    String keyName = it.next().getKey();
                    String value = it.next().getValue();
                    if(fNames.contains(keyName)){
                        PropertyDescriptor pd = null;
                        try {
                            pd = new PropertyDescriptor(keyName, industryType.getClass());
                            Method wM = pd.getWriteMethod();//获得写方法
                            wM.invoke(industryType, value);
                        } catch (IntrospectionException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                }*/
            }
        }catch (Exception e){
            webResult = WebResultUtils.getExceptionCharWebResult("");
        }finally {
            if(webResult==null)
                webResult = WebResultUtils.getFailCharWebResult("参数异常");
        }
        return webResult;
    }

    @ResponseBody
    @RequestMapping("/del")
    public WebResult del(@RequestParam String id){
        WebResult webResult = industryTypeBiz.deleteIndustryTypeById(id);
        return webResult;
    }


    /**
     * 结构:
     * [
     {name: '北京', value: 1, xslkdf: '123', children: [{name: '朝阳', disabled: true, value: 11}, {name: '海淀', value: 12}]},
     {name: '深圳', value: 2, children: [{name: '龙岗', value: 21}]},
     ]
     * */
    @ResponseBody
    @RequestMapping("/queryByTree")
    public Map<String, Object> queryByTree(String packageId,String type,String selVal){
        Map<String,Object> resultMap = new HashMap<>();
        try{
            resultMap = industryTypeBiz.queryByTree(packageId,type,selVal,true,true);
            /*List resultVo = new ArrayList();
            List<IndustryType> industryTypeList = new ArrayList<>();
            if(!Utils.isNullString(packageId)){
                SpeakingPackage speakingPackage = speakingPackageBiz.getSpeakingPackageById(packageId);
                if(speakingPackage!=null){
                    List<String> industryTypeIds = speakingPackage.getHadIndustryTypeId();
                    Map<String,String> map = new HashMap<>();
                    map.put("ids", StringUtils.join(industryTypeIds, ','));
                    industryTypeList = industryTypeBiz.getIndustryTypesList(map);
                }
            }else{
                industryTypeList = industryTypeBiz.getAll();
            }

            if(industryTypeList!=null && !industryTypeList.isEmpty()){
                industryTypeList.forEach(it->{
                    if(Utils.isNullString(it.getParentId())){
                        it.setParentId("0");
                    }
                });

                Map<String,List<IndustryType>> groupByPIdList = industryTypeList.stream()*//*.filter(it->it.getAffectType()== AffectType.PRIVATE)*//*.collect(Collectors.groupingBy(IndustryType::getParentId));
                List<IndustryType> topIndustryType = industryTypeList.stream().filter(it->*//*it.getAffectType()== AffectType.PRIVATE && *//*"0".equals(it.getParentId())).collect(Collectors.toList());
                if(type!=null && "treeNode".equals(type)){
                    List<TreeNodeVo> treeNodeVos = new ArrayList<TreeNodeVo>();
                    topIndustryType.forEach(it->{
                        TreeNodeVo treeNodeVo = recursiveTree(it,groupByPIdList,selVal);
                        if(selVal.contains(treeNodeVo.getValue()))
                                treeNodeVo.setSelected("selected");
                        treeNodeVos.add(treeNodeVo);
                    });
                    resultVo = treeNodeVos;
                }else{
                    List<DTreeNodeVo> dTreeNodeVos = new ArrayList<DTreeNodeVo>();
                    topIndustryType.forEach(it->{
                        dTreeNodeVos.add(recursiveDTree(it,groupByPIdList));
                    });
                    resultVo = dTreeNodeVos;
                }
            }
            if(type!=null && "treeNode".equals(type)){
                resultMap.put("code",0);
                resultMap.put("msg","操作成功");
            }else{
                resultMap.put("status",new HashMap<String, String>() {
                    {
                        put("code", "200");
                        put("message", "操作成功");
                    }
                });
            }
            resultMap.put("data",resultVo);*/
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("status",new HashMap<String, String>() {
                {
                    put("code", "500");
                    put("message", "操作异常 "+e.getMessage());
                }
            });
            resultMap.put("data",null);
        }
        return resultMap;
    }


    /**
     * 递归算法解析成树形结构
     *
     * @param industryType
     * @param groupByPIdList 按parentId 分组后的 集合
     * @return
     * @author jiqinlin
     */
    public TreeNodeVo recursiveTree(IndustryType industryType,Map<String,List<IndustryType>> groupByPIdList,String selVal) {
        //根据cid获取节点对象(SELECT * FROM tb_tree t WHERE t.cid=?)
        TreeNodeVo node = getTreeNodeVo(industryType);

        //查询cid下的所有子节点(SELECT * FROM tb_tree t WHERE t.pid=?)
        List<IndustryType> childTreeNodes = groupByPIdList.get(node.getValue());
        //遍历子节点
        if(childTreeNodes!=null && !childTreeNodes.isEmpty()){
            for (IndustryType child : childTreeNodes) {
                TreeNodeVo n = recursiveTree(child,groupByPIdList,selVal); //递归
                if(selVal.contains(n.getValue()))
                    n.setSelected("selected");
                node.getChildren().add(n);
            }
        }
        return node;
    }


    public DTreeNodeVo recursiveDTree(IndustryType industryType,Map<String,List<IndustryType>> groupByPIdList){
        //根据cid获取节点对象(SELECT * FROM tb_tree t WHERE t.cid=?)
        DTreeNodeVo node = getDTreeNodeVo(industryType);
        //查询cid下的所有子节点(SELECT * FROM tb_tree t WHERE t.pid=?)
        List<IndustryType> childTreeNodes = groupByPIdList.get(node.getId());
        //遍历子节点
        if(childTreeNodes!=null && !childTreeNodes.isEmpty()){
            for (IndustryType child : childTreeNodes) {
                DTreeNodeVo n = recursiveDTree(child,groupByPIdList); //递归
                node.getChildren().add(n);
            }
        }
        return node;
    }

    private TreeNodeVo getTreeNodeVo(IndustryType industryType){
        TreeNodeVo treeNodeVo = new TreeNodeVo();
        treeNodeVo.setValue(industryType.getId());
        treeNodeVo.setName(industryType.getName());
        treeNodeVo.setPid(industryType.getParentId());
        return treeNodeVo;
    }

    private DTreeNodeVo getDTreeNodeVo(IndustryType industryType){
        DTreeNodeVo dTreeNodeVo = new DTreeNodeVo();
        dTreeNodeVo.setId(industryType.getId());
        dTreeNodeVo.setTitle(industryType.getName());
        if(!Utils.isNullString(industryType.getParentId())){
            dTreeNodeVo.setParentId(industryType.getParentId());
        }else{
            dTreeNodeVo.setParentId("0");
        }
        if(!Utils.isNullString(industryType.getBusinessTypeBaseId())){
            dTreeNodeVo.setBusinessTypeBaseId(industryType.getBusinessTypeBaseId());
        }else{
            dTreeNodeVo.setBusinessTypeBaseId("0");
        }

        dTreeNodeVo.setBasicData(new HashMap<String,Object>() {
            {
                put("businessTypeBaseId", dTreeNodeVo.getBusinessTypeBaseId());
            }
        });
        return dTreeNodeVo;
    }

}
